package com.FrameWork.Common;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Looper;
import android.util.Log;
import android.webkit.URLUtil;
import android.widget.Toast;

/**
 * @author Steven Jiang
 * @since 2012年4月1日
 */
public class Updater {

	public Activity activity = null;   
  
    private static final String TAG = "AutoUpdate";   
    private String currentFilePath = "";   
    private String currentTempFilePath = "";   
    private String fileEx = "";   
    private String strURL = "http://127.0.0.1:81/ApiDemos.apk";   
    private ProgressDialog dialog;   
    public Updater(Activity activity, String strURL) {   
        this.activity = activity;   
        this.strURL = strURL;
    }   
    public void check() {   
        if (!isNetworkAvailable(this.activity)) {   
            return;   
        }   
        downloadTheFile(strURL);   
        showWaitDialog();   
    }   
    public static boolean isNetworkAvailable(Context ctx) {   
        try {   
            ConnectivityManager cm = (ConnectivityManager) ctx   
                    .getSystemService(Context.CONNECTIVITY_SERVICE);   
            NetworkInfo info = cm.getActiveNetworkInfo();   
            return (info != null && info.isConnected());   
        } catch (Exception e) {   
            e.printStackTrace();   
            return false;   
        }   
    }   
   
    public void showWaitDialog() {  
    	//Looper.prepare();
    	//if(Looper.myLooper().)
        dialog = new ProgressDialog(activity);   
        dialog.setMessage("发现新版本,正在进行更新");   
        dialog.setIndeterminate(true);
        dialog.setCancelable(true);  
        dialog.show();
       // Looper.loop();
    }   
   
      
    private void downloadTheFile(final String strPath) {   
        fileEx = strURL.substring(strURL.lastIndexOf(".") + 1, strURL.length())   
                .toLowerCase();   
 
        try {   
            if (strPath.equals(currentFilePath)) {   
                doDownloadTheFile(strPath);   
            }   
            currentFilePath = strPath;   
            Runnable r = new Runnable() {   
                public void run() {   
                    try {   
                        doDownloadTheFile(strPath);   
                    } catch (Exception e) {  
                    	Looper.prepare();
                    	if(dialog != null)
                    		dialog.cancel();
                        Toast.makeText(activity, e.getMessage(), 2000).show();
                        Looper.loop();
                    }   
                }   
            };   
            new Thread(r).start();   
        } catch (Exception e) {   
            e.printStackTrace();   
        }   
    }   
    private void doDownloadTheFile(String strPath) throws Exception {   
        
        if (!URLUtil.isNetworkUrl(strPath)) {   
            Log.i(TAG, "getDataSource() It's a wrong URL!");   
        } else {   
            URL myURL = new URL(strPath);   
            URLConnection conn = myURL.openConnection();   
            conn.connect();   
            InputStream is = conn.getInputStream();   
            if (is == null) {   
                throw new RuntimeException("stream is null");   
            }   
            File myTempFile = File.createTempFile("UPDATE", "." + fileEx);   
            currentTempFilePath = myTempFile.getAbsolutePath();   
            FileOutputStream fos = new FileOutputStream(myTempFile);   
            byte buf[] = new byte[128];   
            do {   
                int numread = is.read(buf);   
                if (numread <= 0) {   
                    break;   
                }   
                fos.write(buf, 0, numread);   
            } while (true);   
            Log.i(TAG, "getDataSource() Download  ok...");   
            if(dialog != null)
            {
	            dialog.cancel();   
	            dialog.dismiss();   
          
            }
            openFile(myTempFile);
            try {   
                is.close();   
            } catch (Exception ex) {   
                Log.e(TAG, "getDataSource() error: " + ex.getMessage(), ex);   
            }   
        }   
    }   
    private void openFile(File f) {   
        Intent intent = new Intent();   
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);   
        intent.setAction(android.content.Intent.ACTION_VIEW);   
        String type = getMIMEType(f);   
        intent.setDataAndType(Uri.fromFile(f), type);   
        activity.startActivity(intent);   
    }   
    public void delFile() {   
        Log.i(TAG, "The TempFile(" + currentTempFilePath + ") was deleted.");   
        File myFile = new File(currentTempFilePath);   
        if (myFile.exists()) {   
            myFile.delete();   
        }   
    }   
    private String getMIMEType(File f) {   
        String type = "";   
        String fName = f.getName();   
        String end = fName   
                .substring(fName.lastIndexOf(".") + 1, fName.length())   
                .toLowerCase();   
        if (end.equals("m4a") || end.equals("mp3") || end.equals("mid")   
                || end.equals("xmf") || end.equals("ogg") || end.equals("wav")) {   
            type = "audio";   
        } else if (end.equals("3gp") || end.equals("mp4")) {   
            type = "video";   
        } else if (end.equals("jpg") || end.equals("gif") || end.equals("png")   
                || end.equals("jpeg") || end.equals("bmp")) {   
            type = "image";   
        } else if (end.equals("apk")) {   
            type = "application/vnd.android.package-archive";   
        } else {   
            type = "*";   
        }   
        if (end.equals("apk")) {   
        } else {   
            type += "/*";   
        }   
        return type;   
    }   
}
